package com.frame.servlet;

import com.frame.bean.Img;
import com.frame.service.ImgService;
import com.frame.util.FileUtil;
import com.frame.util.PropUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet(name="UploadServlet",urlPatterns = "/upload")
public class UploadServlet extends HttpServlet {
    private static final long servialVersionUID = 1L;
    private ImgService imgService = new ImgService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //得到上传时的临时文件保存目录
        String tempPath=req.getServletContext().getRealPath(PropUtil.getProperty("upload.tempPath"));
        //取得文件上传的保存目录
        String savePath = req.getServletContext().getRealPath(PropUtil.getProperty("upload.savePath"));
        try {
            File tmpFile = new File(tempPath);
            //如果临时文件不存在，创建临时目录
            if (!tmpFile.exists()) {
                tmpFile.mkdir();
            }
            //创建一个DiskFileItemFactory工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //设置缓冲区大小为100KB,如果不设置默认为10KB
            factory.setSizeThreshold(1024 * 100);
            //设置上传时临时文件的保存目录
            factory.setRepository(tmpFile);
            //创建一个文件上传解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            //监听文件上传进度
            /*upload.setProgressListener(new ProgressListener() {
                @Override
                public void update(long pBytesRead, long pContentLength, int args) {
                    System.out.println("文件大小为：" + pContentLength + "，当前已处理：" + pBytesRead);
                }
            });*/
            //设置上传单个文件的大小的最大值，目前设置为10MB
            upload.setFileSizeMax(1024 * 1024 * 10);
            //设置上传文件总量的最大值，目前设置为10MB
            upload.setSizeMax(1024 * 1024 * 10);
            //使用ServletFileUpload解析器上传数据，解析结果返回的是一个List<FileItem>集合
            List<FileItem> list = upload.parseRequest(req);

            for (FileItem item : list) {
                //判断fileitem中封装的是普通输入项的数据
                if (!item.isFormField()){
                    //获取上传的文件名称
                    String filename = item.getName();
//                    System.out.println(filename);
                    if (filename == null || filename.trim().equals(""))
                        continue;
                    //只保留文件名部分
                    filename = filename.substring(filename.lastIndexOf("\\") + 1);
                    //得到上传文件的扩展名
                    //String fileExtName = filename.substring(filename.lastIndexOf(".") + 1);
                    //如果需要限制上传的文件类型，那么可以通过文件的扩展名来判断上传的文件类型是否合法
                    //System.out.println("上传的文件的扩展名是：" + fileExtName);
                    //获取item中的上传文件的输入流
                    InputStream in = item.getInputStream();
                    //得到文件保存的名称
                    String saveFilename = FileUtil.makeFileName();
                    //得到文件的保存目录
                    String realSavePath = FileUtil.makePath(savePath);
                    //创建一个文件输出流
                    FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename);
                    //创建一个缓冲区
                    byte buffer[] = new byte[1024 * 1024 * 10];
                    //判断输入流中的数据是否已经读完的标识
                    int len = 0;
                    //循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
                    while ((len = in.read(buffer)) > 0) {
                        //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
                        out.write(buffer, 0, len);
                    }
                    //关闭输入流
                    in.close();
                    //关闭输出流
                    out.close();
                    //删除处理文件上传时生成的临时文件
                    item.delete();
                    //创建保存的信息，录入数据库
                    Date date=new Date();
                    DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    String time=format.format(date);
                    Img img = new Img(filename,realSavePath + "\\" + saveFilename,time);
                    imgService.upload(img);
                }
            }
            req.getRequestDispatcher(PropUtil.getProperty("frame.webapp.jsp_path")+"upload_success.jsp").forward(req,resp);
        }catch (FileUploadBase.FileSizeLimitExceededException e) {
            e.printStackTrace();
            req.getRequestDispatcher(PropUtil.getProperty("frame.webapp.jsp_path")+"upload.jsp").forward(req,resp);
            return;
        }catch (FileUploadBase.SizeLimitExceededException e) {
            e.printStackTrace();
            req.getRequestDispatcher(PropUtil.getProperty("frame.webapp.jsp_path")+"upload.jsp").forward(req,resp);
            return;
        }catch (Exception e) {
            req.getRequestDispatcher(PropUtil.getProperty("frame.webapp.jsp_path")+"upload.jsp").forward(req,resp);
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
